'use strict';
const Service = require('egg').Service;
const puppeteer = require('puppeteer');
const { PDFDocument } = require('pdf-lib');
const fs = require('fs');

class Url extends Service{
	async create(data){
        const ctx = this.ctx;

        const browser = await puppeteer.launch({args: ['--disable-setuid-sandbox', '--no-sandbox']});
        const page = await browser.newPage();
        let taskArr = data.url.split('|');
        let pageSize = data.size ? data.size : 'A2';
        let marginLeft = data.marginLeft ? Number(data.marginLeft) : 20;
        let marginTop = data.marginTop ? Number(data.marginTop) : 20;
        let marginBottom = data.marginBottom ? Number(data.marginBottom) : 20;
        let marginRight = data.marginRight ? Number(data.marginRight) : 20;
   
        let pdfDoc = await PDFDocument.create();

        for (let i = 0; i < taskArr.length; i++) {
            await page.goto(taskArr[i], {waitUntil: 'domcontentloaded'}).catch(err => console.log(err));
            await page.waitFor(2000);
            
            let temp_buffer = await page.pdf({
                // path: './app/public/pdf/example.pdf',
                format: pageSize,
                // printBackground: true,  //打印背景图和背景色
                '-webkit-print-color-adjust': 'exact',
                margin: {
                    top: marginTop,
                    bottom: marginBottom,
                    right: marginRight,
                    left: marginLeft
                },
            });

            let temp_doc = await PDFDocument.load(temp_buffer)

            for(let j=0; j<temp_doc.getPageCount(); j++) {
                let [tempPage] = await pdfDoc.copyPages(temp_doc, [j])
                pdfDoc.addPage(tempPage);
            }
        }

        try {
            let fileName = ctx.helper.generateSecret(10);
            // 合成pdf
            fs.writeFileSync('./app/public/pdf/' + fileName +'.pdf', await pdfDoc.save());
            return ctx.helper.success({url:'/public/pdf/' + fileName +'.pdf'},"成功");

        } catch (e) {
            return ctx.helper.fail('异常');
        } finally {
            await browser.close();
        }
	}
}
module.exports = Url;